package cn.virens.library.widget.form.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import java.util.Calendar;
import java.util.Date;

import cn.virens.library.R;
import cn.virens.library.uitls.CalendarUtil;
import cn.virens.library.widget.form.FormTextViewInter;


/**
 * Created by virens on 2017/6/17.
 */
public class FormTextView extends AppCompatTextView implements FormTextViewInter {
    private String name;
    private Object value;
    private int type;

    public FormTextView(Context context) {
        this(context, null);
    }

    public FormTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FormTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        this._initAttrs(attrs, defStyleAttr);
    }

    private void _initAttrs(AttributeSet attrs, int defStyleAttr) {
        final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FormTextView, defStyleAttr, 0);

        this.name = a.getString(R.styleable.FormTextView_name);
        this.type = a.getInt(R.styleable.FormTextView_type, 0);

        a.recycle();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Object getValue() {
        return value;
    }

    @Override
    public void setValue(Object value) {
        this.value = value;
        if (value == null) {
            this.setText("");
        } else if (type == 1) {
            if (value instanceof Number) {
                this.setText(CalendarUtil.format(new Date(((Number) value).longValue()), "yyyy-MM-dd"));
            } else {
                this.setText("????-??-??");
            }
        } else if (type == 2) {
            if (value instanceof Number) {
                this.setText(((Number) value).intValue() > 0 ? "是" : "否");
            } else if ("true".equals(value)) {
                this.setText("是");
            } else if ("1".equals(value)) {
                this.setText("是");
            } else if ("on".equals(value)) {
                this.setText("是");
            } else {
                this.setText("否");
            }
        } else if (value instanceof Date) {
            this.setText(CalendarUtil.format((Date) value, "yyyy-MM-dd"));
        } else if (value instanceof Calendar) {
            this.setText(CalendarUtil.format((Calendar) value, "yyyy-MM-dd"));
        } else if (value instanceof Boolean) {
            this.setText((Boolean) value ? "是" : "否");
        } else {
            this.setText(value.toString());
        }
    }
}
